import pymysql

class DataBase():   #类名和模块名一致，robot导入时不用写类名@@@@@
    def __init__(self):
        try:
            self.conn = pymysql.connect(host='127.0.0.1',
                                port=3306,
                                user='root',
                                password='admin',
                                db='job_worm',
                                charset='utf8' )
        except pymysql.err.OperationalError as e:
            print(e)

    def insert_one(self, insert_sql,record):
        # 使用cursor()方法获取操作游标
        cur = self.conn.cursor()
        try:
            #示例
            # insertSql = 'INSERT INTO users(username, userpass, nickname) VALUES(%s, %s, %s) '
            # rows = cur.execute(insertSql, ("shuke", "123", "舒克"))
            #返回插入的行数
            cur.execute(insert_sql,record)
            # 提交
            self.conn.commit()
            return cur.lastrowid
        except Exception as e:
            # 错误回滚
            self.conn.rollback()


    def select_list(self, select_sql,condition=None):
        # 使用cursor()方法获取操作游标
        cur = self.conn.cursor()
        try:
            cur.execute(select_sql,condition)  # 执行sql语句
            results = cur.fetchall()  # 获取查询的所有记录
            return results
        except Exception as e:
            self.conn.rollback()

    def select_one(self, select_sql,condition=None):
        # 使用cursor()方法获取操作游标
        cur = self.conn.cursor()
        try:
            cur.execute(select_sql,condition)  # 执行sql语句
            result = cur.fetchone()  # 获取查询的所有记录
            return result
        except Exception as e:
            self.conn.rollback()

    def close_conn(self):
        self.conn.close()